<template>
    <div>
        <el-row>
            <el-col :span="14">
                <div class="grid-content bg-purple">
                    <el-form :inline="true" :model="queryMap" class="demo-form-inline">
                        <el-form-item label="订餐部门" v-if="role==='管理员'">
                            <el-select v-model="queryMap.deptId"  clearable>
                                <el-option
                                    v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName"
                                    :value="dept.deptId"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="发起员工">
                            <el-input v-model="queryMap.empName" clearable></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="search">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
            <el-col :span="7" :offset="3" >
                <el-button-group>
                    <el-button icon="el-icon-success" type="primary" @click="openPass">批量通过</el-button>
                    <el-button icon="el-icon-error" type="primary" @click="openReject">批量退回</el-button>
                    <el-button-group>
                        <el-button icon="el-icon-more" type="primary" @click="openDetail">查看详情</el-button>
                    </el-button-group>
                </el-button-group>
            </el-col>
        </el-row>
        <el-table
            :data="tableData"
            :height="530"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
            >
            <el-table-column
                prop="orderId"
                type="selection"
            >

            </el-table-column>
            <el-table-column
                label="序号"
                type="index"
                width="60"
                align="center"
            >
            </el-table-column>
            <el-table-column
                label="发起人"
                prop="empName"
                width="140"
            >
            </el-table-column>
            <el-table-column
                label="部门名称"
                prop="deptName"
                width="100"
            >
            </el-table-column>
            <el-table-column
                label="订餐人员"
                prop="members"
                width="180"
            >
            </el-table-column>
            <el-table-column
                label="总金额"
                prop="totalprice"
                width="100"
                :formatter="formatPrice"
                align="right"
            >
            </el-table-column>
            <el-table-column
                label="订餐日期"
                prop="orderdate"
                width="140"
                align="center"
            >
            </el-table-column>
            <el-table-column
                label="订餐备注"
                prop="orderNote"
                width="150"
            >
            </el-table-column>
            <el-table-column
                label="订餐状态"
                prop="status"
                width="180"
            >
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="pass(scope.$index, scope.row)">通过</el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="reject(scope.$index, scope.row)">退回</el-button>
                </template>
            </el-table-column>

        </el-table>
        <!-- 分页 -->
        <el-pagination
            :current-page="queryMap.page"
            :page-size="queryMap.limit"
            :page-sizes="[10, 20, 50, 100, 200]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
        </el-pagination>
        <OrderDetail
            :isPass ="isPass"
            @submitForm="save"
            :detailData="detailData"
            :detail-visible.sync="detailVisible"
        ></OrderDetail>
        <BatchReview
            :formVisible.sync=formVisible
            :is-pass="isPass"
            :review-table="reviewTable"
            @submitReview="submitReview"
        ></BatchReview>
    </div>
</template>

<script>
import OrderDetail from "@/components/OrderDetail.vue";
import MealForm from "@/views/meal/MealForm.vue";
import BatchReview from "@/views/OrderReview/BatchReview.vue";
export default {
    name: "OrderReview",
    components: {BatchReview, MealForm, OrderDetail},
    data() {
        return {
            //查询条件
            queryMap: {
                page: 1,  // 当前页码
                limit: 10, // 每页条数
                empName:'',//员工名称
                deptId: '',//部门id
                status: ''//查询的订单状态
            },
            // 总条数
            total: 0,
            /*statusList:[],*/
            tableData: [],
            // 审核表单显隐
            formVisible: false,
            // 详情信息显隐
            detailVisible:false,
            //标志通过还是退回,false为退回
            isPass: true,
            //复选框选中的数据
            multipleSelection: [],
            deptList:[],
            //订单的详情信息
            detailData: {
                    reviewList:[],
                    mealList: [],
                    statusId:''
            },
            reviewTable:[],
        }
    },
    methods: {
        // 点击查询按钮
        search() {
            const self = this
            // 重置页面未第一页
            this.queryMap.page = 1;
            this.getOrderList();
        },
        // 查询所有订餐状态
        getStatusList() {
            const self = this;
            this.$http.get('statusList').then(res => {
                self.statusList = res.data;
            }).catch(error => {
                this.$message.error('查询订餐状态失败，请联系管理员')
            })
        },
        // 查询所有部门
        getDeptList() {
            const self = this;
            this.$http.get('deptList').then(res => {
                self.deptList = res.data;
            }).catch(error => {
                this.$message.error('查询部门失败，请联系管理员')
            })
        },
        // 每页条数改变，val是改变后的每页条数
        handleSizeChange(val) {
            this.queryMap.limit = val;
            this.queryMap.page = 1;
            this.getDeptList();
        },
        // 页码改变，val是修改后的页面
        handleCurrentChange(val) {
            this.queryMap.page = val;
            this.getDeptList();
        },
        //点击复选框触发,val是勾选中的数据
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        setQueryMap() {
            // 根据用户角色设置部门ID，如果是部门经理，只查询本部门订单
            if (this.role === '部门经理') {
                this.queryMap.deptId = parseInt(this.deptId); // 限制为当前用户的部门ID
                this.queryMap.statusId = 1;
            } else if (this.role === '管理员') {
                this.queryMap.deptId = null; // 系统管理员查看公司订单
                this.queryMap.statusId = 2;
            }
        },
        //获取审核的餐品列表
        getOrderList() {
            const self = this
            this.$http.post('getReviewOrderByPage', this.queryMap).then(res => {
                self.tableData = res.data.orders
                self.total = res.data.count
            }).catch(() => {
                this.$message.error('获取订餐列表失败，请联系管理员')
            })
        },
        //单独审核
        pass(index,row){
            let reviewData = []
            this.$prompt('请输入审核意见', '通过', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                // 检查输入的审核意见是否为空
                if (!value) {
                    this.$message({
                        type: 'error',
                        message: '审核意见不能为空，请输入内容'
                    });

                    // 重新调用 prompt 以便用户再次输入
                    setTimeout(() => {
                        this.pass(index, row);
                    }, 1000);
                    return;
                }
                //获取选中行的主键
                reviewData.push(
                    {
                        "orderId":row.orderId,
                        "reviewerId":parseInt(this.$store.state.user.empId),
                        "reviewerName":this.$store.state.user.empName,
                        "reviewResult":1,
                        "reviewNote":value
                    }
                )
                this.reviewOrderBatch(reviewData)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消审核'
                });
            });
        },
        reject(index,row){
            let reviewData = []
            this.$prompt('请输入审核意见', '退回', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                //获取选中行的主键
                reviewData.push(
                    {
                        "orderId":row.orderId,
                        "reviewerId":parseInt(this.$store.state.user.empId),
                        "reviewerName":this.$store.state.user.empName,
                        "reviewResult":0,
                        "reviewNote":value
                    }
                )
                this.reviewOrderBatch(reviewData)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消审核'
                });
            });
        },
        openPass(){
            const self = this
            //判断是否选中了一条数据,
            if (self.multipleSelection.length === 0) {
                self.$message({
                    type: 'warning',
                    message: "请选择要通过的订餐记录"
                })
            }else {
                this.isPass=true
                this.reviewTable=[]
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    this.reviewTable.push(
                        {
                            orderId:this.multipleSelection[i].orderId,
                            empName:this.multipleSelection[i].empName,
                            deptName:this.multipleSelection[i].deptName,
                            members:this.multipleSelection[i].members,
                            totalprice:this.multipleSelection[i].totalprice,
                            orderNote:this.multipleSelection[i].orderNote,
                        }
                    )
                }
                //打开批量审核对话框
                self.formVisible=true
            }
        },
        openReject(){
            const self = this
            //判断是否选中了一条数据,
            if (self.multipleSelection.length === 0) {
                self.$message({
                    type: 'warning',
                    message: "请选择要退回的订餐记录"
                })
            }else {
                this.isPass=false
                this.reviewTable=[]
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    this.reviewTable.push(
                        {
                            orderId:this.multipleSelection[i].orderId,
                            empName:this.multipleSelection[i].empName,
                            deptName:this.multipleSelection[i].deptName,
                            members:this.multipleSelection[i].members,
                            totalprice:this.multipleSelection[i].totalprice,
                            orderNote:this.multipleSelection[i].orderNote,
                        }
                    )
                }
                //打开批量审核对话框
                self.formVisible=true
            }
        },
        formatPrice(row, column, cellValue, index) {
            // 使用 toFixed 方法来格式化小数，保留两位小数
            // 注意：toFixed 返回的是一个字符串
            return cellValue.toFixed(2);
        },
        //处理批量审核的数据
        submitReview(reviewNotes){
            let reviewData=[]
            //判断是退回还是通过
            if (this.isPass) {
                for (let i = 0; i < reviewNotes.length; i++) {
                    reviewData.push(
                        {
                            "orderId": reviewNotes[i].orderId,
                            "reviewerId":parseInt(this.$store.state.user.empId),
                            "reviewerName": this.$store.state.user.empName,
                            "reviewResult": 1,
                            "reviewNote": reviewNotes[i].reviewNote
                        }
                    )
                }
            }else {
                for (let i = 0; i < reviewNotes.length; i++) {
                    reviewData.push(
                        {
                            "orderId": reviewNotes[i].orderId,
                            "reviewerId":parseInt(this.$store.state.user.empId),
                            "reviewerName": this.$store.state.user.empName,
                            "reviewResult": 0,
                            "reviewNote": reviewNotes[i].reviewNote
                        }
                    )
                }
            }
            this.reviewOrderBatch(reviewData)
        },

        //批量审核方法
        reviewOrderBatch(reviewData){
            this.$http.post("/reviewOrder",reviewData).then(res=>{
                if (res.data ==='success'){
                    this.$message({
                        type:'success',
                        message:'保存成功'
                    })

                }else {
                    this.$message.error("保存失败")
                }
                //刷新列表
                this.queryMap.page=1;
                this.getOrderList()
                this.formVisible=false
            }).catch((e)=>{
                this.$message.error("出现错误,请联系管理员")
                this.getOrderList()
                this.formVisible=false
            })
        },
        // 保存新增
        save(reviewData) {
            this.$http.post("reviewOrder",reviewData).then(res =>{
                if (res.data==='success'){
                    this.$message({
                        type:'success',
                        message:'订餐审核成功'
                    })
                    //关闭弹框
                    this.formVisible = false
                    //刷新列表
                    this.queryMap.page=1;
                    this.getOrderList();
                }else {
                    this.$message.error("订餐审核失败")
                }
            }).catch(()=>{
                this.$message.error("审核失败,请联系管理员")
            })
        },

        //打开订单详情
        openDetail(){
            const self = this
            //判断是否选中了一条数据,
            if (self.multipleSelection.length === 0) {
                self.$message({
                    type: 'warning',
                    message: "请选择要查看的数据"
                })
            } else if (self.multipleSelection.length > 1) {
                this.$message({
                    type: 'warning',
                    message: "只能选择一条数据"
                })
            } else {
                //获取选中行的主键
                let orderId = this.multipleSelection[0].orderId;
                this.detailVisible=true

                this.$http.get("/getOrderDetailById/" + orderId).then(res => {
                    //根据主键获取要修改的数据
                    this.detailData = res.data
                    this.detailVisible=true
                }).catch(error => {
                    self.$message.error("获取订餐失败")
                })
            }
        }
    },
    computed: {
        role() {
            return this.$store.state.user.role
        },
        deptId() {
            return this.$store.state.user.deptId
        },
        reviewerName(){
            return this.$store.state.user.empName
        },
        reviewResult(){
            if (this.isPass){
                return 1;
            }else {
                return 0;
            }
        }
    },
    created() {
        this.setQueryMap();
        this.getStatusList();
        this.getOrderList();
        this.getDeptList();
    }
}
</script>

<style scoped>

</style>